package com.bytecodezz.jc.canvastest.ui

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

@Composable
fun CanvasView(modifier: Modifier = Modifier) {
    Canvas(modifier = modifier) {
        // 将DrawScope转换成系统原生的Canvas绘制
        drawIntoCanvas { canvas ->
            val paint = Paint().apply {
                color = Color.Black
                strokeWidth = 3f
                isAntiAlias = true
                style = PaintingStyle.Stroke
            }
            //先保存，方便绘制完成后在恢复
            canvas.save()
            //将坐标原点转换到屏幕中心
            canvas.translate(center.x, center.y)
            //原点上绘制一个位置参考圆形
            canvas.drawCircle(Offset(0f, 0f), 5f, paint)
            //这里绘制冰墩
            val ovalSize = Size(500.0f, 600.0f)
            // 1、绘制一个宽x高 500x600 的椭圆
            canvas.drawOval(
                Rect(
                    -ovalSize.width / 2.0f,
                    -ovalSize.height / 2.0f,
                    ovalSize.width / 2.0f,
                    ovalSize.height / 2.0f
                ), paint
            )
            //绘制左耳
            canvas.drawArc(
                rect = Rect(Offset(-180f, -310f), Size(90f, 110f)),
                startAngle = -215f,//起始角度
                sweepAngle = 185f,//旋转的角度
                useCenter = false,//不以圆弧的中心点为参考
                paint = paint
            )
            //绘制右耳
            canvas.drawArc(
                rect = Rect(Offset(95f, -310f), Size(90f, 110f)),
                startAngle = -160f,
                sweepAngle = 205f,
                useCenter = false,
                paint = paint
            )
            canvas.restore()
        }
    }
}

@Preview
@Composable
fun PreviewCanvas() {
    Surface(
        Modifier
            .background(Color.White)
            .width(1000.dp)
            .height(1000.dp)
    ) {
        CanvasView()
    }
}

